package cn.how2j.trend.service;

import cn.how2j.trend.pojo.Index;
import cn.how2j.trend.util.SpringContextUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "indexes")
public class IndexService {
    private List<Index> indexes;
    @Autowired
    RestTemplate restTemplate;




    @HystrixCommand(fallbackMethod = "third_part_not_connected")
    public List<Index> fresh(){
        indexes = fetch_indexes_from_third_part();//先获取数据
        IndexService service = SpringContextUtil.getBean(IndexService.class);
        service.remove();
        return service.store();
    }

    @Cacheable(key = "'all_codes'")
    public List<Index> store() {
        System.out.println(this);//谁调用就是谁
        return indexes;
    }

    @CacheEvict(allEntries = true)//该注解用来标记需要清除缓存的元素
    public void remove() {

    }

    //获取数据
    public List<Index> fetch_indexes_from_third_part(){
        List<Map> temp = restTemplate.getForObject("http://127.0.0.1:8090/indexes/codes.json", List.class);
        return  map2Index(temp);
    }

    //断路器方法
    public List<Index> third_part_not_connected(){
        Index index = new Index();
        index.setName("无效指数代码");
        index.setCode("000000");
        List<Index> list  = new ArrayList<>(16);
        list.add(index);
        return list;
    }

    private List<Index> map2Index(List<Map> temp){
        List<Index> indices = new ArrayList<>(16);
        for (Map map : temp) {
            Index index = new Index();
            index.setCode((String) map.get("code"));
            index.setName((String) map.get("name"));
            indices.add(index);
        }
        return indices;
    }
}
